﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BLL;
using Logic;
using Logic.ClarizenSvc;
using System.Web.Services.Protocols;

namespace ClarizenGadget.Controllers
{
    public class LoginController : Controller
    {
        public ActionResult TokenLogin(String accessToken)
        {
            Session[Constants.LoginKey] = true;

            Log.Write("TokenLogin action");

            if(!string.IsNullOrEmpty(Users.CurrentClarizenID))
                return Json(true, JsonRequestBehavior.AllowGet);
            else
                return Json(false, JsonRequestBehavior.AllowGet);
        }
        //
        // GET: /Login/
        [HttpGet]
        public ActionResult Login()
        {
            Users.SetClarizenSession("", null);

            ViewBag.Goto = ClarizenUtils.GetGoTo();
            ViewBag.ResetToken = !string.IsNullOrEmpty(Request["logout"]);
            return View();
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Login(String tbUserName, String tbPassword)
        {
            ViewBag.Token = Users.CurrentUserID.HasValue ? HttpUtility.UrlEncode(BLL.Encryption.Encrypt(Users.CurrentUserID.ToString())) : "";
            
            if (String.IsNullOrEmpty(tbUserName) || String.IsNullOrEmpty(tbPassword))
            {
                ViewBag.ErrorMesage = "* " + "You must specify a user name and password.";
                return View();
            }

            
            Logic.LoginComponent.LoginResponse lr;
            if (Users.Login(tbUserName, tbPassword, Logic.Constants.ConduitKey, out lr))
            {
                var url = ClarizenUtils.GetGoTo();
                return Redirect(url);
            }
            else
            {
                ViewBag.ErrorMesage = "*" + lr.Message;
                return View();
            }
        }

        [HttpPost]
        public ActionResult Logout()
        {
            Users.Logout();
            return Json(new GadgetResponse<Object> { ErrorMessage = "Not logged in", Status = GadgetResponseStatus.Not_Logged_In, RedirectUrl = Constants.CurrentUrl + "/login/login?logout=1&goto=" + ClarizenUtils.GetGoTo() });
        }
        
    }
}
